<?php

/**
 * DBMan
 * 1.LCache功能
 * 2.强制主库查询
 * 3.数据格式转换
 */

class Data_DB
{
    private $_db;

    public function __construct()
    {
        $host = DB_HOST;
        $user = DB_USER;
        $pass = DB_PASS;
        $database = DB_NAME;

		$db = $this->_db = new mysqli($host,$user,$pass,$database);
		if (!$db)
		{
			throw new Exception("Could not connect \'$host\' - " . mysqli_connect_error() );
		}

		if (!$db->query("set names 'utf8';"))
		{
			throw new Exception("Set Names 'utf8' Error - " . $db->errno .":". $db->error, $db->errno );
		}
    }

    /**
     * 单条sql查询
     * @param cacheTime: <0 - 强制更新LCache，读主库;
     *                    0 - 不缓存到LCache;
     *                   >0 - 缓存到LCache，时长为$cacheTime
     */
    public function sQuery($kind , $hintId , $sql)
    {
		$db = $this->_db;
		$res = $db->query($sql);
		if (false === $res)
		{
			throw new Exception("excute '$sql' error - " . $db->errno .":". $db->error, $db->errno );
		}

        $data = array();
        $rownum = 0;
		if (is_object($res) && $res->num_rows != 0)
		{
			while ($row = $res->fetch_array(MYSQLI_ASSOC))
			{
				$data[] = $row;
			}
			$rownum = $res->num_rows;
		}

		return array('data' => $data,
                    'rownum' => $rownum,
                    'insertid' => $db->insert_id,
                    'affectedrows' => $db->affected_rows);
    }

    /**
     * 多条sql查询
     */
    public function mQuery($kind , $hintId , $sqls)
    {
		$db = $this->_db;
		$sqls = implode(';', $sqls);
		$res = $db->multi_query($sqls);
		if (!$res)
		{
			throw new Exception("excute '$sqls' error - " . $db->errno .":". $db->error, $db->errno );
		}

        $result = array();
		do {
			$data = array();
			$rownum = 0;
			$resSet = $db->store_result();
			if (is_object($resSet) && $resSet->num_rows>0)
			{
				while ($row = $resSet->fetch_array(MYSQLI_ASSOC))
				{
					$data[] = $row;
				}
				$rownum = $resSet->num_rows;
				$resSet->close();
			}
			else if ($db->errno)
			{
				throw new Exception("store result for '$sqls' error - " . $db->errno .":". $db->error, $db->errno );
			}
			$result[] = array('data' => $data,
                    'rownum' => $rownum,
                    'insertid' => $db->insert_id,
                    'affectedrows' => $db->affected_rows);
		} while ($db->next_result());

		return $result;
    }
}
?>